package com.guoqi.keepsign.base

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.donkor.deepnight.utils.ImageLoadUtils
import com.donkor.deepnight.utils.showToast
import com.guoqi.keepsign.IPConfig
import com.guoqi.keepsign.IPConfig.LG
import com.guoqi.keepsign.IPConfig.MZT
import com.guoqi.keepsign.R
import com.guoqi.keepsign.album.AlbumUI
import com.guoqi.keepsign.ligui.LiguiAlbumUI
import com.guoqi.keepsign.mzt.MztZtUI
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements


class CommonAdapter(context: Activity?, list: ArrayList<CommonBean>?) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    val TAG = "CommonAdapter"

    var mContext: Activity? = null
    private var mList: ArrayList<CommonBean>? = null
    private var mInflater: LayoutInflater? = null
    private val TYPE_ITEM: Int? = 0
    private val TYPE_FOOTER: Int? = 1

    //专题
    private var ztList = ArrayList<CommonBean>()

    var imageList = ArrayList<ImageInfo>()
    //上拉加载更多
    val PULLUP_LOAD_MORE: Int? = 0
    //正在加载中
    val LOAD_MORE: Int? = 1
    //没有加载更多 隐藏
    val NO_LOAD_MORE: Int? = 2

    //上拉加载更多状态-默认为0
    private var mLoadMoreStatus: Int? = 0

    init {
        mContext = context
        mList = list
        mInflater = LayoutInflater.from(context)
    }

    override fun getItemCount(): Int {
        return mList?.size ?: 0
    }

    override fun getItemViewType(position: Int): Int {
        return if (position + 1 == itemCount) {
            TYPE_FOOTER!!
        } else {
            TYPE_ITEM!!
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            TYPE_ITEM -> return CommonHolder(mInflater?.inflate(R.layout.item_common, parent, false)!!)
            TYPE_FOOTER -> return FooterViewHolder(mInflater?.inflate(R.layout.load_more, parent, false)!!)
        }
        return CommonHolder(mInflater?.inflate(R.layout.item_common, parent, false)!!)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val title: String? = mList?.get(position)?.title ?: ""
        if (holder is CommonHolder) {
            if (title.isNullOrEmpty()) {
                holder.tvTitle.setBackgroundColor(0)
            } else {
                holder.tvTitle.text = title
            }
            mList?.get(position)?.src?.let {
                ImageLoadUtils.display(mContext, holder.ivPic, it)
                holder.ivPic.setOnClickListener {
                    if (mList?.get(position)?.src.isNullOrEmpty()) {
                        mContext?.showToast("链接失效")
                    } else {
                        startPhotoActivity(title!!, mList?.get(position)?.src!!, mList?.get(position)?.href!!)
                    }
                }
            }
        } else if (holder is FooterViewHolder) {
            when (mLoadMoreStatus) {
                PULLUP_LOAD_MORE -> holder.tvLoadText?.text = "上拉加载更多"
                LOAD_MORE -> holder.tvLoadText?.text = "正在加载更多..."
                NO_LOAD_MORE -> holder.linLoadLayout?.visibility = View.GONE
            }
        }
    }

    class CommonHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var ivPic: ImageView = itemView?.findViewById<ImageView>(R.id.iv_pic) as ImageView
        var tvTitle: TextView = itemView?.findViewById<TextView>(R.id.tv_title) as TextView
    }

    class FooterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var pbLoad: ProgressBar? = null
        var tvLoadText: TextView? = null
        var linLoadLayout: LinearLayout? = null

        init {
            pbLoad = itemView?.findViewById(R.id.pb_load)
            tvLoadText = itemView?.findViewById(R.id.tv_load_text)
            linLoadLayout = itemView?.findViewById(R.id.lin_load_layout)
        }
    }

    fun changeMoreStatus(status: Int) {
        mLoadMoreStatus = status
        notifyDataSetChanged()
    }

    private fun startPhotoActivity(title: String, picUrl: String, href: String = "") {
        //其他
        //https://i.meizitu.net/thumbs/2013/06/3597_8a20733egw1e4vqvcb0xxj20jz5uwe86_236.jpg
        //自拍/街拍
        //https://wxt.sinaimg.cn/mw1024/9d52c073gy1g2cxksbun9j20sg0zk7wh.jpg
        //https://wxt.sinaimg.cn/mw1024/9d52c073gy1g2cxlido1dj20sg16oal5.jpg
        //专题
        //https://i.meizitu.net/pfiles/tagimg/zhifu-tag.jpg

        imageList.clear()
        if (picUrl.contains("-tag.")) {
            handlerMZT2(title, picUrl)
        } else if (picUrl.contains("meizitu.")) {
            handlerMZT(title, picUrl)
        } else if (picUrl.contains("img.mm24.cc")) {
            handlerLigui(title, href)
        }
    }


    private fun handlerMZT(title: String, picUrl: String) {
        val index = picUrl.lastIndexOf("/") + 1
        val fileName = picUrl.substring(index)
        val index2 = fileName.indexOfFirst { it.toString() == "_" }
        val part = fileName.substring(0, index2)
        //177207
        Thread(Runnable {
            val doc: Document = Jsoup.connect(MZT + part)
                    .timeout(IPConfig.DEFAULT_TIMEOUT).userAgent(IPConfig.DEFUALT_USERAGENT).get()
            val pageSingle: Elements? = doc.getElementsByClass("pagenavi")
            val list = pageSingle?.map { it.select("span").html() } as ArrayList<String>
            val s = list.toString()
            val pageSize = s.substring(s.indexOf("…") + 1, s.indexOf("下一页")).replace("\n", "").toInt()

            val imgSingle: Elements? = doc.getElementsByClass("main-image")
            var url = ""
            imgSingle?.map { it.select("img") }
                    ?.forEach {
                        url = it.attr("src").replace("\n", "")
                    }
            for (i in 1..pageSize) {
                val page =
                        if (i < 10) {
                            "0$i"
                        } else {
                            i.toString()
                        }
                imageList.add(ImageInfo("${url.replace("01.", "$page.")}"))
                Log.e(TAG, "${url.replace("01.", "$page.")}")
            }
            var intent = Intent(mContext, AlbumUI::class.java)
            intent.putExtra("title", title)
            intent.putExtra("imageList", imageList)
            mContext?.startActivity(intent)
        }).start()
    }


    private fun handlerMZT2(title: String, picUrl: String) {
        //https://i.meizitu.net/pfiles/tagimg/zhifu-tag.jpg
        val index = picUrl.lastIndexOf("/") + 1
        val fileName = picUrl.substring(index)
        val index2 = fileName.indexOfFirst { it.toString() == "-" }
        val part = fileName.substring(0, index2)
        //zhifu
        var intent = Intent(mContext, MztZtUI::class.java)
        intent.putExtra("url", "$MZT/tag/$part/page/")
        mContext?.startActivity(intent)
    }


    private fun handlerLigui(title: String, picUrl: String) {
        //http://www.zhuanai.cc/ligui/3026.html
        val part = picUrl.substring(picUrl.lastIndexOf("/") + 1).replace(".html", "")
        val pageList = ArrayList<String>()
        Thread(Runnable {
            val doc: Document = Jsoup.connect("""$LG$part.html""")
                    .timeout(IPConfig.DEFAULT_TIMEOUT).userAgent(IPConfig.DEFUALT_USERAGENT).get()
            val pageSingle: Elements? = doc.getElementsByClass("link_pages")
            val span = pageSingle?.select("span")!!.html()
            val pageSize = span.split("页:")[0].replace("共", "").toInt()

            for (i in 1..pageSize) {
                val page = if (i == 1) {
                    ""
                } else {
                    "_${i}"
                }
                pageList.add("$LG$part$page.html")
                Log.e(TAG, "$LG$part$page.html")
            }
            val intent = Intent(mContext, LiguiAlbumUI::class.java)
            intent.putExtra("title", title)
            intent.putExtra("pageList", pageList)
            mContext?.startActivity(intent)
        }).start()
    }
}